const config = require('../../config/api.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },
  bindGetUserInfo(e) {
    if (e.detail.userInfo) {
      this.getLoginInfo().then(res => {
        // console.log(wx.getStorageSync('token'))
        wx.request({
          url: config.userInfo,
          method: 'POST',
          data: {
            nickName: getApp().globalData.userInfo.userName,
            headImgUrl: getApp().globalData.userInfo.headImgUrl
          },
          header: {
            Accept: 'application/json',
            Authorization: 'Bearer ' + wx.getStorageSync('token'),
            'content-type': 'application/json',
            APPID: 28
          },
          success(res) {
            getApp().globalData.first = res.data.first;
            wx.setStorageSync("appraiser", res.data.appraiser);
            wx.switchTab({
              url: '/pages/index/index',
            });
            wx.hideLoading();
          }
        })
      }).catch(res => {

      });
    } else {
      wx.showModal({
        title: '警告',
        content: '你点击了拒绝按钮',
        showCancel: true,
        cancelText: "取消",
        cancelColor: '#000000',
        confirmText: "返回授权",
        confirmColor: "#000000",
        success: function(res) {}
      })
    }
  },
  getLoginInfo() {
    // 登录
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: '登录中',
      })

      wx.getSetting({
        success: res => {
          // 获取授权
          wx.getUserInfo({
            success: res => {
              getApp().globalData.userInfo = {
                userName: res.userInfo.nickName,
                headImgUrl: res.userInfo.avatarUrl
              }
              wx.login({
                success: res => {
                  // 获取用户信息
                  wx.request({
                    url: 'https://api.mokyun.com/wxusers/authenticate/miniProgram',
                    method: 'POST',
                    data: {
                      code: res.code
                    },
                    header: {
                      APPID: 28
                    },
                    success(res) {
                      if (res.data.token) {
                        wx.setStorageSync('token', res.data.token);
                        resolve()
                      }
                    }
                  })
                }
              })
            }
          })
        }
      })

    })
  }
})